# -*- coding: utf-8 -*-

 ###############################################
 ##                                             ##
 ##   Access                                     ##
 ##                                              ##
 ##                                              ##
 ##   for Taller Básico aka tásic                ##
 ##   by Críptidos Digitales                     ##
 ##   GPL (c)2010                                ##
  ##                                             ##
    ###############################################

"""
Contains the class that defines the dialog that captures the system authentication data.

"""

import sys
from PyQt4 import QtCore, QtGui

import access_ui
from cdWidgets import errors

import man as model


class Form(QtGui.QDialog):

    @property
    def app(self):
        return self.__app

    @property
    def mode(self):         ## Normal, Remoto, Recovery
        return self.__mode

    @property
    def serverName(self):
        return "%s" % self.ui.pathED.text()

    @property
    def userName(self):
        return "%s" % self.ui.usernameED.text()

    @property
    def password(self):
        return "%s" % self.ui.passwordED.text()

    def __init__(self, *args, **kwds): # print 'access.Form.__init__()'
        if kwds.has_key('app'):
            self.__app = kwds.pop('app')
        else:
            self.__app = {}

        if kwds.has_key('mode'):
            self.__mode = kwds.pop('mode')
        else:
            self.__mode = u'Normal'

        if kwds.has_key('user'):
            user = kwds.pop('user')
        else:
            user = ""

        if args:
            title = args[0]
        else:
            title = ""

        QtGui.QDialog.__init__(self)

        self.ui = access_ui.Ui_Dialog()
        self.ui.setupUi(self)

        self.setWindowTitle(self.app.info['title'])
        self.setWindowIcon(QtGui.QIcon("imagenes/logo.png"))

        if self.app.config.pull('layout', 'accessWindowState'):
            self.restoreGeometry(QtCore.QByteArray().fromBase64(self.app.config.pull('layout', 'accessWindowState')))
        else:
            self.resize(375, 550)

        if title:
            self.ui.titleLB.setText(title)

        self.ui.logoLB.setText("%s" % self.app.info['title'])
        self.ui.logoLB.setStyleSheet("background-image:url(imagenes/logo.png)")

        ## Username
        self.ui.usernameLB.setText(QtGui.QApplication.translate("Dialog", "Nombre de usuario", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.usernameED.setSymbolsAllowed(False)
        self.ui.usernameED.setText(u"")
        self.ui.usernameED.setPrefijoMensaje(u"El nombre de usuario")
        self.connect(self.ui.usernameED, QtCore.SIGNAL('textEdited(QString)'), self.actualizaStatus)

        ## Password
        self.ui.passwordLB.setText(QtGui.QApplication.translate("Dialog", "Contraseña", None, QtGui.QApplication.UnicodeUTF8))
        self.ui.passwordED.setText(u"")
        self.ui.passwordED.setPrefijoMensaje(u"La contraseña")
        self.connect(self.ui.passwordED, QtCore.SIGNAL('textEdited(QString)'), self.actualizaStatus)

        ## New password
        self.ui.newPasswordED.setPrefijoMensaje(u"La contraseña nueva")
        self.connect(self.ui.newPasswordED, QtCore.SIGNAL('textEdited(QString)'), self.actualizaStatus)

        ## Password again
        self.ui.passwordAgainED.setPrefijoMensaje(u"La confirmación de contraseña")
        self.connect(self.ui.passwordAgainED, QtCore.SIGNAL('textEdited(QString)'), self.actualizaStatus)

        ## Recovery question
        self.ui.questionED.setPrefijoMensaje(u"La pregunta")
        self.connect(self.ui.questionED, QtCore.SIGNAL('textEdited(QString)'), self.actualizaStatus)

        ## Recovery answer
        self.ui.answerED.setPrefijoMensaje(u"La respuesta")
        self.connect(self.ui.answerED, QtCore.SIGNAL('textEdited(QString)'), self.actualizaStatus)

        # Server path
        # self.connect(self.ui.pathBU, QtCore.SIGNAL('clicked()'), self.selectPath)

        self.ui.usernameFR_layout.show()
        # if model.usernameActive():
            # self.ui.usernameFR_layout.show()
        # else:
            # self.ui.usernameFR_layout.hide()

        self.ui.passwordChangeFR_layout.hide()
        self.ui.recoveryFR_layout.hide()
        self.ui.serverFR_layout.hide()

        if self.mode == u'firstRun':
            self.ui.passwordFR_layout.hide()
            self.ui.passwordChangeFR_layout.show()
            self.ui.recoveryFR_layout.show()

        if self.mode == u'Remoto':
            self.ui.serverFR_layout.show()

        if self.mode == u'Recovery':
            self.ui.titulo.setText(u'Recuperación de Contraseña')
            self.ui.passwordFR_layout.hide()
            self.ui.recoveryFR_layout.show()

        if self.mode == u'change':
            self.ui.titleLB.setText(u'Cambio de Contraseña')
            self.ui.passwordLB.setText(u'Contraseña actual')
            self.ui.passwordChangeFR_layout.show()

        if self.mode == u'server':
            self.ui.titleLB.setText(u'Dirección del servidor')
            self.ui.serverFR_layout.show()


        ## Accept
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("imagenes/CheckMark.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ui.acceptBU.setIcon(icon)
        self.ui.acceptBU.setIconSize(QtCore.QSize(32,32))
        self.connect(self.ui.acceptBU, QtCore.SIGNAL('clicked()'), self.acceptClicked)

        ## Cancel
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("imagenes/Cancel.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ui.cancelBU.setIcon(icon)
        self.ui.cancelBU.setIconSize(QtCore.QSize(32,32))
        self.connect(self.ui.cancelBU, QtCore.SIGNAL('clicked()'), self.cancel)

        self.setTabOrder(self.ui.usernameED, self.ui.passwordED)
        self.setTabOrder(self.ui.passwordED, self.ui.newPasswordED)
        self.setTabOrder(self.ui.newPasswordED, self.ui.passwordAgainED)
        self.setTabOrder(self.ui.passwordAgainED, self.ui.questionED)
        self.setTabOrder(self.ui.questionED, self.ui.answerED)
        self.setTabOrder(self.ui.answerED, self.ui.pathED)
        self.setTabOrder(self.ui.pathED, self.ui.cancelBU)
        # self.setTabOrder(self.ui.pathBU, self.ui.pathBU)
        self.setTabOrder(self.ui.cancelBU, self.ui.acceptBU)

        self.status = 0
        self.tries = 0

        self.filename = ''

        self.actualizaStatus()

        self.ui.usernameED.setFocus()


    def actualizaStatus(self, *args):
        m = "access.Form.actualizaStatus()"
        if self.isValid():
            self.ui.acceptBU.setEnabled(True)
            self.ui.acceptBU.setToolTip(u"")
        else:
            self.ui.acceptBU.setEnabled(False)
            self.ui.acceptBU.setToolTip(self.mensajes)


    def acceptClicked(self):
        m = "access.Form.acceptClicked()"
        # print (1), m

        self.tries += 1
        if self.tries <= 3:

            data = [unicode(self.ui.usernameED.text()), unicode(self.ui.passwordED.text())]

            if not self.ui.serverFR_layout.isHidden():
                data.append(unicode(self.ui.pathED.text()))

            result = model.createSession(data)

            if result == '00000':
                self.app.config.push('layout', 'accessWindowState', self.saveGeometry().toBase64())
                self.accept()

            elif result == '20400':     #! Unknown host
                if self.ui.serverFR_layout.isHidden():
                    ## retry with url
                    self.ui.serverFR_layout.show()
                QtGui.QMessageBox.critical(self, self.app.info['title'], u"No pude contactar al servidor.\n\nIntenta de nuevo", QtGui.QMessageBox.Ok)

            elif result == '20250':     #! Autentication failed
                QtGui.QMessageBox.critical(self, self.app.info['title'], u"Los datos no son válidos\n\nIntenta de nuevo", QtGui.QMessageBox.Ok)
                self.ui.passwordED.selectAll()

            elif result == '42504':     #! No database
                QtGui.QMessageBox.critical(self, self.app.info['title'], u"No existe la base de datos\n\nInforma al administrador del sistema", QtGui.QMessageBox.Ok)


            else:
                print (1), m
                print sys.exc_info()
                raise result

        elif not self.ui.recoveryFR_layout.isVisible():
            self.ui.recoveryFR_layout.show()
            question, answer = model.getRecovery()
            if question:
                self.ui.questionFR.hide()
                self.ui.answerLB.setText(question)
                self.ui.answerED.setFocus()
                self.ui.recoveryFR_layout.show()
                self.ui.passwodFR_layout.hide()


    def autenticate(self, username="", password=""):
        pass


    def cancel(self):           # print 'access.Form.cancel()'
        self.reject()


    def isValid(self):          # print "access.Form.isValid()"
        valida = True
        self.mensajes = ""

        if not self.ui.usernameFR_layout.isHidden():
            if not self.ui.usernameED.isValid:
                valida = False
                self.mensajes += u"%s\n" % self.ui.usernameED.message()

        if not self.ui.passwordFR_layout.isHidden():
            # self.ui.passwordED.setExternalValidation(True, u"")
            if not self.ui.passwordED.isValid:
                valida = False
                self.mensajes += u"%s\n" % self.ui.passwordED.message()
            # if not model.testPassword("%s" % self.ui.passwordED.text()):
                # valida = False
                # self.mensajes += u"La contraseña actual no es válida\n"
                # self.ui.passwordED.setExternalValidation(False, u"Esta no es la contraseña actual\n")

        if not self.ui.passwordChangeFR_layout.isHidden():
            if self.ui.newPasswordED.text() != self.ui.passwordAgainED.text():
                self.ui.passwordAgainED.setExternalValidation(False, u"La contraseña nueva y la confirmación deben ser iguales\n")
            else:
                self.ui.passwordAgainED.setExternalValidation(True, u"")

            if not self.ui.newPasswordED.isValid:
                valida = False
                self.mensajes += u"%s\n" % self.ui.newPasswordED.message()

            if not self.ui.passwordAgainED.isValid:
                valida = False
                self.mensajes += u"%s\n" % self.ui.passwordAgainED.message()

        if not self.ui.recoveryFR_layout.isHidden():
            if not self.ui.questionED.isValid:
                valida = False
                self.mensajes += u"%s\n" % self.ui.questionED.message()

            if not self.ui.answerED.isValid:
                valida = False
                self.mensajes += u"%s\n" % self.ui.answerED.message()

        self.mensajes.rstrip(u'\n')

        return valida


    # def selectPath(self):
        # self.filename = QtGui.QFileDialog.getOpenFileName(self, "Seleccione", "", "")
        # self.ui.pathED.setText(self.filename)
        # model.changeSession(self.filename)


    def setData(self, *args):
        self.ui.passwordED.setText(args[0])


    def setMode(self, mode):
        self.__mode = mode
        if self.mode == u'Remoto':
            self.ui.serverFR_layout.show()
        else:
            self.ui.serverFR_layout.hide()

        if self.mode == u'Recovery':
            self.ui.recoveryFR_layout.show()
        else:
            self.ui.recoveryFR_layout.hide()




"""
toDo

No se ha implementado la funcionalidad de la pregunta y respuesta



"""